package tuioZones;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

import processing.core.PApplet;

public class Category {
	
	//public static String library = "data";
	public static String library = "/Users/fwalter/Documents/Processing/mfhci/data";
	private static String ending = ".jpg";
	
	private String name;
	private HashMap<String,Puzzle> puzzles;
	
	public Category(PApplet myPApplet, File directory) {
		this.name = directory.getName();
		puzzles = new HashMap<String,Puzzle>();
		for(File f : directory.listFiles(new ImageFilter())) {
			if(f.isDirectory() || f.isHidden())
				continue;
			
			Card c = new Card(f.getName().substring(0,f.getName().lastIndexOf(ending)));
			c.setBgImage(myPApplet.loadImage(f.getAbsolutePath()),GamingArea.CARD_WIDTH,GamingArea.CARD_HEIGHT);
            c.setCategory(this);
			
			String title = f.getName().substring(0,f.getName().lastIndexOf(ending) - 2);
			
			Puzzle puzzle = puzzles.get(title);
			
			if(puzzle == null) {
				puzzle = new Puzzle(title);
				puzzle.setCA(c);
			} else {
				puzzle.setCB(c);
			}
			
			puzzles.put(title,puzzle);
			
		}
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	public ArrayList<Card> getInitialSetOfCards(int count) {
		if(count % 2 == 1) 
			return null;
		
		ArrayList<Card> ret = new ArrayList<Card>();
		
		ArrayList<Puzzle> pz = new ArrayList<Puzzle>(puzzles.values());
		
		for(int i = 0; i < count; i = i + 2) {
			int get = (int) (Math.random() * puzzles.size());
			Puzzle p = pz.get(get);
			if(p != null && p.isValid()) {
				ret.add(p.getCA());
				ret.add(p.getCB());
			} else {
			}
		}

		return ret;
	}
	
	public class ImageFilter implements FileFilter {

		public boolean accept(File pathname) {
			String name = pathname.getName();
			return name.endsWith("A"+ending) || name.endsWith("B"+ending);
		}
	}
}
